﻿using System;
using System.Collections.Generic;

using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SceneEngine;
using Microsoft.Xna.Framework.Input;

namespace SceneEditor
{
    class CameraWidget
    {
        protected Model model;
        protected Matrix[] bones;

        protected Vector3 position;
        protected Vector3 scale;

        protected bool visible;

        public Vector3 Position
        {
            get { return position; }
            set { position = value; }
        }
        public Vector3 Scale
        {
            get { return scale; }
            set { scale = value; }
        }
        public Vector3 Rotation { get; set; }

        public bool Visible
        {
            get { return visible; }
            set { visible = value; }
        }

        protected Matrix World
        {
            get
            {
                return Matrix.CreateScale(scale) * Matrix.CreateTranslation(position);
            }
        }

        public CameraWidget() 
        {
            this.model = EditorGlobals.EditorContent.Load<Model>("Editor\\translate axis");

            this.bones = new Matrix[this.model.Bones.Count];
            this.model.CopyAbsoluteBoneTransformsTo(bones);

            this.scale = new Vector3(0.07f);

            this.visible = true;
        }

        public void Draw()
        {
            if (visible)
            {
                ICamera camera = EngineGlobals.Camera;

                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (BasicEffect effect in mesh.Effects)
                    {
                        Matrix camera_aligned_world;
                        Matrix viewToWorld = Matrix.Invert(camera.View);

                        camera_aligned_world = bones[mesh.ParentBone.Index] * World;
                        camera_aligned_world.Translation = camera.Position + camera.Forward;

                        Vector3 offset = new Vector3(1.1f, 0.65f, -1f);
                        camera_aligned_world.Translation = camera_aligned_world.Translation + Vector3.TransformNormal(offset, viewToWorld);

                        effect.World = camera_aligned_world;
                        effect.View = camera.View;
                        effect.Projection = camera.Projection;
                    }

                    mesh.Draw();
                }
            }
        }
    }
}
